package xin.nick.common.serialize;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.text.DecimalFormat;

/**
 * Double 保留两位小数的json处理
 *
 * @author Nick
 * @date 2022/9/4
 */
public class Double2Serializer extends JsonSerializer<Double> {

    private DecimalFormat df = new DecimalFormat("#0.00");
    private String noneNumber = "-";
    public Double2Serializer() {
    }

    @Override
    public void serialize(Double o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (o.toString() != null && !noneNumber.equals(o)) {
            Double dd = Double.parseDouble(o.toString());
            jsonGenerator.writeString(df.format(dd));
        } else {
            jsonGenerator.writeString(o.toString());
        }
    }

}